环境
- Ubuntu 16.04
- Python3
- gcc/g++
- jsoncpp-0.10.7.tar.gz(可以在github上该项目的release下载)
安装过程
- 可以通过将jsoncpp编译为静态库或动态库的方式使用,也可以通过引用其头文件的方式来使用。
- 在这里采用第二种方式,首先需要生成dist文件夹,里面有jsoncpp.cpp和两个头文件。 - 1 
 2- cd jsoncpp-0.10.7 
 python amalgamate.py #此步会生成dist文件夹
- 然后就可以自己写程序来使用jsoncpp了,要包含两个文件才行。 - 1 
 2- #include "json/json.h" 
 #include "jsoncpp.cpp"
- 具体的程序内容可以看下一节”使用方法” 
- 通过以下命令来编译运行程序1 
 2g++ -o test test.cpp -I./jsoncpp-0.10.7/dist/ # -I根据dist所在的路径来写 
 ./test
使用方法
- 通过程序来展现jsoncpp的使用方式 - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 using namespace std;
 int main(){
 Json::Value json_temp;
 json_temp["name"]=Json::Value("haha");
 json_temp["age"]=Json::Value(23);
 Json::Value root;
 root["key1"]=json_temp;
 root["key2"].append(1234);
 root["key2"].append("abcd");
 root["key2"].append(1.234);
 //fast无格式输出
 Json::FastWriter fast_writer;
 cout<<"fastwriter: "<<endl;
 cout<<fast_writer.write(root)<<endl;
 //style格式化输出
 Json::StyledWriter style_writer;
 cout<<"stylewriter: "<<endl;
 cout<<style_writer.write(root)<<endl;
 //string输出
 string str=fast_writer.write(root);
 cout<<"string out:"<<endl<<str<<endl;
 //从字符串解析json
 Json::Reader reader;
 Json::Value res;
 if(!reader.parse(str,res)){
 cout<<"parse error"<<endl;
 }else{
 cout<<"parse successfully"<<endl;
 cout<<"key1 is :"<<endl<<res["key1"]<<endl;
 }
 }
- 输出结果如下: - 1 
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21- fastwriter: 
 {"key1":{"age":23,"name":"haha"},"key2":[1234,"abcd",1.234]}
 stylewriter:
 {
 "key1" : {
 "age" : 23,
 "name" : "haha"
 },
 "key2" : [ 1234, "abcd", 1.234 ]
 }
 string out:
 {"key1":{"age":23,"name":"haha"},"key2":[1234,"abcd",1.234]}
 parse successfully
 key1 is :
 {
 "age" : 23,
 "name" : "haha"
 }
参考
欢迎与我分享你的看法。
转载请注明出处:http://taowusheng.cn/